package com.zhonglian.nourish.view.d.adapter;

import android.content.Context;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.zhonglian.nourish.R;
import com.zhonglian.nourish.utils.GlideUtils;
import com.zhonglian.nourish.utils.LogUtil;
import com.zhonglian.nourish.utils.ToastUtils;
import com.zhonglian.nourish.utils.dialogs.DialogConfirmUtil;
import com.zhonglian.nourish.utils.dialogs.DialogLoadingUtil;
import com.zhonglian.nourish.view.a.activity.PaySubmit2Activity;
import com.zhonglian.nourish.view.d.activity.EvaluateActivity;
import com.zhonglian.nourish.view.d.activity.MyOrderDetailsActivity;
import com.zhonglian.nourish.view.d.bean.OrderBean;
import com.zhonglian.nourish.view.d.presenter.DPresenter;
import com.zhonglian.nourish.view.login.viewer.IPublicViewer;

import java.util.ArrayList;
import java.util.List;

/**
 * Created : Yx
 * Time : 2019/3/26 18:10
 * Describe : 订单列表
 */
public class MyOrderAdapter extends RecyclerView.Adapter {

    private Context mContext;
    private List<OrderBean> mLists;
    private List<String> mTimes = new ArrayList<>();//模拟毫秒
    //用于退出 Activity,避免 Countdown，造成资源浪费。
    private List<CountDownTimer> countDownCounters;

    public MyOrderAdapter(Context context) {
        this.mContext = context;
        mTimes.add("1792000");
        mTimes.add("28000");
        this.countDownCounters = new ArrayList<>();
    }

    public void setData(List<OrderBean> list) {//设置数据
        this.mLists = list;
        clearTimer();
        notifyDataSetChanged();
    }

    public void clearTimer() {
        if (countDownCounters != null && countDownCounters.size() > 0) {//清理定时
            for (int i = 0; i < countDownCounters.size(); i++) {
                countDownCounters.get(i).cancel();
            }
            countDownCounters.clear();
        }
    }

    @Override
    public int getItemCount() {
        if (mLists != null && mLists.size() > 0) {
            return mLists.size();
        }
        return 0;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_my_order, viewGroup, false);
        return new AdapterHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, final int position) {
        final AdapterHolder holder = (AdapterHolder) viewHolder;
        GlideUtils.setImageCircle(mLists.get(position).getDetail().get(0).getGoods_image(), holder.myorder_img);
        holder.myorder_price.setText("¥" + mLists.get(position).getAllprice());
        holder.myorder_num.setText("订单号：" + mLists.get(position).getOrderid());
        holder.myorder_count.setText("共" + mLists.get(position).getDetail().size() + "个包裹");
        holder.myorder_cd.setVisibility(View.GONE);//倒计时
        holder.myorder_select.setVisibility(View.GONE); //查看物流
        holder.myorder_cancel.setVisibility(View.GONE);  //取消订单
        holder.myorder_details.setVisibility(View.GONE);//查看订单
        holder.myorder_payment.setVisibility(View.GONE);//立即付款
        holder.myorder_evaluate.setVisibility(View.GONE); //去评价
        holder.myorder_delete.setVisibility(View.GONE); //删除订单
        holder.myorder_confirm.setVisibility(View.GONE); //确认收货
        //按钮显示
        setViewType(holder, position);
        //待付款时间倒计时
        if ("1".equals(mLists.get(position).getPaystatus())) {
            setViewTime(holder.myorder_cd, mLists.get(position).getShengyu_createtime());
        }


        holder.itemView.setOnClickListener(v -> {
            //订单详情
            mContext.startActivity(new Intent(mContext, MyOrderDetailsActivity.class).putExtra("orderId", mLists.get(position).getId()));
        });
        holder.myorder_details.setOnClickListener(v -> {
            //订单详情
            mContext.startActivity(new Intent(mContext, MyOrderDetailsActivity.class).putExtra("orderId", mLists.get(position).getId()));
        });


        holder.myorder_select.setOnClickListener(v1 -> {
            //查看物流
        });
        holder.myorder_cancel.setOnClickListener(v1 -> {
            //取消订单
            DialogConfirmUtil.showConfirmDefault(mContext, "确定取消吗?", "", new DialogConfirmUtil.OnConfirmCallback() {
                @Override
                public void onSuccess(String str) {
                    orderCancel(position);
                }

                @Override
                public void onFail(String str) {

                }
            });
        });
        holder.myorder_payment.setOnClickListener(v1 -> {
            //立即付款
            mContext.startActivity(new Intent(mContext, PaySubmit2Activity.class).putExtra("orderId", mLists.get(position).getId()).putExtra("inPriceCount", mLists.get(position).getAllprice()));
        });
        holder.myorder_evaluate.setOnClickListener(v1 -> {
            //去评价
            mContext.startActivity(new Intent(mContext, EvaluateActivity.class).putExtra("mOrder", mLists.get(position)));

        });
        holder.myorder_delete.setOnClickListener(v1 -> {
            //删除订单
            DialogConfirmUtil.showConfirmDefault(mContext, "确定删除吗?", "", new DialogConfirmUtil.OnConfirmCallback() {
                @Override
                public void onSuccess(String str) {
                    orderDelete(position);
                }

                @Override
                public void onFail(String str) {

                }
            });
        });
        holder.myorder_confirm.setOnClickListener(v1 -> {
            //确认收货
            DialogConfirmUtil.showConfirmDefault(mContext, "确认收货吗?", "", new DialogConfirmUtil.OnConfirmCallback() {
                @Override
                public void onSuccess(String str) {
                    orderConfirm(position);
                }

                @Override
                public void onFail(String str) {

                }
            });
        });

    }


    /**
     * 订单类型
     *
     * @param holder
     */
    private void setViewType(final AdapterHolder holder, int position) {
        switch (mLists.get(position).getPaystatus()) {
            case "1"://待付款
                holder.myorder_cd.setVisibility(View.VISIBLE);//倒计时
                holder.myorder_payment.setVisibility(View.VISIBLE); //立即付款
                holder.myorder_cancel.setVisibility(View.VISIBLE); //取消订单
                holder.myorder_time.setText(mLists.get(position).getCreatetime() + "　待付款");
                break;
            case "2"://待发货
                holder.myorder_details.setVisibility(View.VISIBLE); //取消订单
                holder.myorder_time.setText(mLists.get(position).getCreatetime() + "　待发货");
                break;
            case "3"://待收货
                holder.myorder_select.setVisibility(View.VISIBLE); //查看物流
                holder.myorder_confirm.setVisibility(View.VISIBLE); //确认收货
                holder.myorder_time.setText(mLists.get(position).getCreatetime() + "　待收货");
                break;
            case "4"://待评价
                holder.myorder_select.setVisibility(View.VISIBLE); //查看物流
                holder.myorder_evaluate.setVisibility(View.VISIBLE); //去评价
                holder.myorder_time.setText(mLists.get(position).getCreatetime() + "　待评价");
                break;
            case "5"://已完成
                holder.myorder_select.setVisibility(View.VISIBLE); //查看物流
                holder.myorder_delete.setVisibility(View.VISIBLE); //删除订单
                holder.myorder_time.setText(mLists.get(position).getCreatetime() + "　已完成");
                break;
            case "6"://已取消
                holder.myorder_delete.setVisibility(View.VISIBLE); //删除订单
                holder.myorder_time.setText(mLists.get(position).getCreatetime() + "　已取消");
                break;
        }

    }

    /**
     * 待付款状态时间倒计时
     *
     * @param textView
     * @param times//秒数
     */
    private void setViewTime(TextView textView, String times) {
        long countTime = Long.parseLong(times) * 1000;//毫秒
        LogUtil.iYx("--倒计时开始：" + countTime);
        CountDownTimer cdTimer = new CountDownTimer(countTime, 1000) {
            @Override
            public void onTick(long inTime) {
                long m = inTime / 1000 / 60;
                long s = inTime / 1000 % 60;
                String strM = m + "";
                String strS = s + "";
                if (strM.length() == 1) {
                    strM = "0" + strM;
                }
                if (strS.length() == 1) {
                    strS = "0" + strS;
                }
                textView.setText("剩余" + strM + ":" + strS);
            }

            @Override
            public void onFinish() {
                textView.setText("剩余00:00");
            }
        };
        cdTimer.start();
        countDownCounters.add(cdTimer);
    }


    /**
     * 取消订单
     */
    private void orderCancel(int position) {
        DialogLoadingUtil.showLoading(mContext);
        DPresenter.getInstance().orderCancels(mLists.get(position).getId(), new IPublicViewer() {
            @Override
            public void onSuccess(String str) {
                DialogLoadingUtil.hidn();
                mLists.get(position).setPaystatus("6");
                notifyDataSetChanged();
            }

            @Override
            public void onFail(String str) {
                DialogLoadingUtil.hidn();
                ToastUtils.showToastApplication(str);
            }
        });

    }

    /**
     * 删除订单
     */
    private void orderDelete(int position) {
        DialogLoadingUtil.showLoading(mContext);
        DPresenter.getInstance().orderDeletes(mLists.get(position).getId(), new IPublicViewer() {
            @Override
            public void onSuccess(String str) {
                DialogLoadingUtil.hidn();
                mLists.remove(position);
                notifyDataSetChanged();
            }

            @Override
            public void onFail(String str) {
                DialogLoadingUtil.hidn();
                ToastUtils.showToastApplication(str);
            }
        });
    }

    /**
     * 确认收货
     */
    private void orderConfirm(int position) {
        DialogLoadingUtil.showLoading(mContext);
        DPresenter.getInstance().orderConfirms(mLists.get(position).getId(), "4", new IPublicViewer() {
            @Override
            public void onSuccess(String str) {
                DialogLoadingUtil.hidn();
                mLists.get(position).setPaystatus("4");
                notifyDataSetChanged();
            }

            @Override
            public void onFail(String str) {
                DialogLoadingUtil.hidn();
                ToastUtils.showToastApplication(str);
            }
        });
    }


    private class AdapterHolder extends RecyclerView.ViewHolder {
        private ImageView myorder_img;
        private TextView myorder_price, myorder_time, myorder_num, myorder_count;
        private TextView myorder_cd, myorder_select, myorder_cancel, myorder_details, myorder_payment, myorder_evaluate, myorder_delete, myorder_confirm;

        private AdapterHolder(@NonNull View itemView) {
            super(itemView);
            myorder_img = itemView.findViewById(R.id.item_myorder_img);
            myorder_price = itemView.findViewById(R.id.item_myorder_price);
            myorder_time = itemView.findViewById(R.id.item_myorder_time);
            myorder_num = itemView.findViewById(R.id.item_myorder_num);
            myorder_count = itemView.findViewById(R.id.item_myorder_count);
            myorder_cd = itemView.findViewById(R.id.item_myorder_cd);
            myorder_select = itemView.findViewById(R.id.item_myorder_select);
            myorder_cancel = itemView.findViewById(R.id.item_myorder_cancel);
            myorder_details = itemView.findViewById(R.id.item_myorder_details);
            myorder_payment = itemView.findViewById(R.id.item_myorder_payment);
            myorder_evaluate = itemView.findViewById(R.id.item_myorder_evaluate);
            myorder_delete = itemView.findViewById(R.id.item_myorder_delete);
            myorder_confirm = itemView.findViewById(R.id.item_myorder_confirm);
        }
    }
}
